<template>
  <div class="register-container">
    <el-card class="register-card" shadow="hover">
      <h3 class="register-title">注册</h3>
      <el-form :model="registerForm" @submit.prevent="handleRegister">
        <el-form-item>
          <el-input v-model="registerForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="registerForm.password" placeholder="密码" type="password" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="registerForm.confirmPassword" placeholder="确认密码" type="password" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister">注册</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {reactive} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';

const router = useRouter();

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
});

const handleRegister = async () => {
  // 验证密码和确认密码是否匹配
  if (registerForm.password !== registerForm.confirmPassword) {
    ElMessage.error('密码和确认密码不匹配');
    return;
  }

  try {
    const response = await fetch('http://localhost:3000/api/register', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        username: registerForm.username,
        password: registerForm.password
      })
    });

    const data = await response.json();
    if (response.ok) {
      ElMessage.success('注册成功');
      await router.push('/login'); // 注册成功后跳转到登录页面
    } else {
      ElMessage.error(data.message || '注册失败');
    }
  } catch (error) {
    ElMessage.error('网络错误');
    console.error('Register error:', error);
  }
};

const handleCancel = () => {
  router.push('/login'); // 取消注册，返回登录页面
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f2f2f2;
}

.register-card {
  width: 400px;
  padding: 20px;
}

.register-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}
</style>
